package com.lejin.order.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.lejin.order.service.impl.CourseOrderConfirmServiceImpl;
import com.lejin.order.util.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("pay")
public class PayController {
    @Autowired
    private CourseOrderConfirmServiceImpl courseOrderConfirmService;
    @RequestMapping("success")
    public String callback(HttpServletRequest request) throws Exception {

        System.out.println("--------------------");
        //当订单支付成功后，微信支付平台会向此接口发送支付信息
        ServletInputStream inputStream = request.getInputStream();
        StringBuffer buffer = new StringBuffer();
        byte[] bs = new byte[1024];
        int len = -1;
        while((len = inputStream.read(bs))!=-1){
            buffer.append(new String(bs,0,len));
        }
        String s = buffer.toString();  // xml文件格式数据
        //s就是微信平台传递的支付信息
        //将微信发送的xml字符串格式的信息 转换成map集合
        Map<String, String> msgMap = WXPayUtil.xmlToMap(s);
        if("SUCCESS".equals( msgMap.get("result_code") ) &&
                "SUCCESS".equals( msgMap.get("return_code") )){
            //付款成功
            String orderId = msgMap.get("out_trade_no");
            System.out.println("订单："+orderId+"   支付成功！");
            //根据订单id修改数据库订单状态为 "待发货"
            //略
            //响应微信支付平台
            //推送消息给前端
            WebSocketServer.sendMsg(orderId,"1");
//            Session session = WebSocketServer.sessionMap.get(orderId);
//            if(session!=null){
//                session.getBasicRemote().sendText("1");
//            }
            HashMap<String,String> resp = new HashMap<>();
            resp.put("return_code","success");
            resp.put("return_msg","OK");
            resp.put("appid",msgMap.get("appid"));
            resp.put("result_code","success");
            return WXPayUtil.mapToXml(resp);
        }
        return null;
    }

}
